package net.wangds.imagecomp.comp;

import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 抠图工具.
 * <p></p>
 *
 * @author 王东石 2020/8/24 14:09.
 */
@Component
public class OfficeSealComp {

    /**
     * 抠图.
     * @param src 输入图.
     * @param original 是否保持颜色.
     *                 false时指保留红色（黑色为底).
     * @param alpha original为true时，颜色的透明度.
     * @param backgroundColor 背景色.
     *                        <p>透明值为：{@linkplain Transparency#TRANSLUCENT}.</p>
     * @return 输出图.
     */
    public BufferedImage matting(BufferedImage src, boolean original, float alpha, int backgroundColor){
        int w = src.getWidth();
        int h = src.getHeight();

        BufferedImage out = new BufferedImage(w,h, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g=out.createGraphics();
        out = g.getDeviceConfiguration().createCompatibleImage(w, h, backgroundColor);

        g = out.createGraphics();

        g.setBackground(new Color(0,0,0,100));

        for(int i=0;i<w;i++){
            for(int j=0;j<h;j++){
                int color = src.getRGB(i,j);
                int red = color&0xFF0000;
                int green = color&0x00FF00;
                int blue = color&0x0000FF;
                int r = red>>16;
                int gr = green>>8;
                int b = blue;
                if( r<0xC0&&((r>0x90&&r>gr&&r>b&&(r-gr>0x18||r-b>0x18))||(r<=0x90&&r>gr&&r>b&&r-gr>0x18&&r-b>0x18))){
                    g.setColor(original?new Color(r, 0, 0, alpha):new Color(color) );
                    g.drawRect(i, j, 1, 1);
                }
            }
        }
        return out;
    }



}
